﻿using System;
using System.Threading.Tasks;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using MediatR;
using Casamiel.Common;
using System.Threading;
using Casamiel.Common.Extensions;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Casamiel.Domain;
using System.Globalization;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// Un bind member card command hander.
    /// </summary>
    public sealed class UnBindMemberCardCommandHandler : BaseCommandHandler, IRequestHandler<UnBindMemberCardCommand, Zmodel>
    {
        /// <summary>
        /// Initializes a new instance of the
        /// </summary>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="memberCard">Member card.</param>
        /// <param name="memberService"></param>
        /// <param name="mobileCheckCode">Mobile check code.</param>
        /// <param name="userLogService">User log service.</param>
        public UnBindMemberCardCommandHandler(IIcApiService iicApiService,
            IMemberCardService memberCard, IMemberService memberService,
              IMobileCheckCode mobileCheckCode, IUserLogService userLogService) : base(iicApiService, memberCard, memberService, mobileCheckCode, userLogService)
        {
        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<Zmodel> Handle(UnBindMemberCardCommand request, CancellationToken cancellationToken)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            var sucess = await MobileCheckCode.CheckSmsCodeAsync(request.Mobile, request.Yzm, false).ConfigureAwait(false);

            if (sucess["code"].ToString() != "0") {
                //obj["code"] = -2;
                //obj["msg"] = "验证码输入不正确!";
                return new Zmodel { code = sucess["code"].ToString().ToInt32(0), msg = sucess["msg"].ToString() };
            }
            // var mcard = _context.MemberCard.FirstOrDefault(c => c.Mobile == mobile && c.IsBind == true);
            var mcard = await MemberCardService.FindAsync<ICasaMielSession>(request.Cardno, request.Mobile).ConfigureAwait(false);
            if (mcard == null) {
                //return BadRequest();
                return new Zmodel { code = -16, content = "", msg = "会员卡已经解绑" };
            }
            if (mcard.CardNO != request.Cardno) {
                return new Zmodel { code = -10, content = "", msg = "卡号不存在" };
            }
            if (mcard.CardType == "2") {
                var result = await IcApiService.GetCardBalance(request.Cardno, $"{request.Source}099".ToInt32(0)).ConfigureAwait(false);
                if (result.code == 0) {
                    var vc = JsonConvert.DeserializeObject<JObject>(result.content);
                    if (Convert.ToDecimal(vc["directmoney"].ToString(), CultureInfo.CurrentCulture) > 0) {
                        return new Zmodel { code = -11, content = "", msg = "卡内有余额不能解绑！" };
                    }

                    //                "totalmoney": 598.01,
                    //"directmoney": 598.01,
                    //"othermoney": 0,
                }
            }
            var a = await IcApiService.Unicregist(mcard.CardNO, mcard.Mobile, request.Source).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            if (a.code == 0 || a.code == 103)//14手机号和会员卡号不匹配(已解）
            {
                mcard.IsBind = false;
                mcard.UnBindTime = DateTime.Now;
                await MemberCardService.UpdateAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                //await _memberCard.UnitOfWork.SaveChangesAsync();
                // _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
                var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"解绑会员卡,卡号:[{request.Cardno}]", OPTime = DateTime.Now, UserName = request.Mobile, UserIP = request.UserIP };
                await UserLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                return new Zmodel { code = 0, content = "", msg = "解绑成功！" };
            }

            return a;
        }

    }
}
